#include "bg_biped.h"
#include "bg_scene.h"
#include "bones/biped_instance.h"

#include "script/scripthelper.h"
#include "script/write_lua.h"
#include "graphics/graphics.h"

#include "util/timer.h"				// log
#include "util/log.h"				// log
#include "util/common_macros.h"		// macros
#include "util/mmgr.h"		    

#include <cassert>
#include <algorithm>

using namespace background;
using namespace script;


BGBiped::BGBiped(BGScene*	pScene) : 
	BGElement(pScene),
	m_pBiped(NULL)
{
	m_Size = math::Vec2(0.1f, 0.1f);
	m_Type = ELEMENT_BIPED;
}
BGBiped::~BGBiped()
{
	UTIL_SAFE_DELETE(m_pBiped);
}

void	BGBiped::FlushImages()
{
	// flush all sprites in the biped
	if (m_pBiped)
	{
		m_pBiped->FlushImages();
	}
}
void	BGBiped::Render(const math::Vec2& Offset, float	Scale) 
{
	if (m_pBiped)
	{
		m_pBiped->OBJECT_SCALE = Scale;
		m_pBiped->SetPos((GetScreenPos(Offset, Scale)));
		m_pBiped->Render(math::Vec2(0,0));
	}
}
void	BGBiped::Tick(float dt)
{
	if (m_pBiped)
	{
		m_pBiped->Tick(dt);
		// generate particles as well?
	}
	BGElement::Tick(dt);
}

void	BGBiped::SetAnimation(const std::string& File)
{
	m_Biped = File;
	if (m_Biped.empty()) return;

	UTIL_SAFE_DELETE(m_pBiped);
	m_pBiped = new bones::BipedInstance();
	m_pBiped->SetAnimation(File);
	m_pBiped->LoadDefaults();

	math::Vec2	Min, Max;
	m_pBiped->GetExtents(Min, Max);
	m_Size = Max-Min;
	RecalcBoundingBox();
}
void	BGBiped::RecalcBoundingBox() 
{
	m_ClipSize = m_Size*0.5f;
}

void	BGBiped::Load(LuaPlus::LuaObject& Obj)
{
	BGElement::Load(Obj);
	m_Biped = ScriptHelper::GetTableString(Obj, "Biped");
	bool		Flipped = ScriptHelper::GetTableBool(Obj, "Flipped", false);
	SetAnimation(m_Biped);
	if (m_pBiped)
	{
		m_pBiped->SetFlipped(Flipped);
	}
}

void	BGBiped::Save(script::WriteLua* pWL)
{
	BGElement::Save(pWL);
	pWL->WritePair("Biped", m_Biped);
	if (m_pBiped)
	{
		pWL->WritePair("Flipped", m_pBiped->IsFlipped());
	}
}

void	BGBiped::OnElementReset()
{
	if (m_pBiped) m_pBiped->ForceAnimationTime(0.0f);
}
